package com.su.dolphin.utils;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ViewHolderUtil
{
    @SuppressWarnings ("unchecked")
    /**
     *  getView 中:
     *  if (convertView == null) {
     *      convertView = ViewHolderUtil.inflateView(R.layout.newslist_item, parent);
     *  }
     *  TextView textView = ViewHolderUtil.findViewById(convertView, R.id.newsTitle);
     * 
     */
    public static <T extends View> T findViewById(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }
    
    public static View inflateView(int redId, ViewGroup parent) {
        View view = LayoutInflater.from(parent.getContext()).inflate(redId, parent, false);
        return view;
    }
    
    /**
     * 通过制定的 layout xml 生成一个view
     * 
     * @param redId
     *            layout的id
     * @param context
     * @return
     */
    public static View inflateView(int redId, Context context) {
        View view = LayoutInflater.from(context).inflate(redId, null, false);
        return view;
    }
}
